<?php

namespace app\controller\api\activity;

use app\common\model\activity\NewActivityCouponRelevance;
use app\common\model\store\coupon\StoreCouponUser;
use app\common\repositories\activity\NewActivityProductRepository;
use think\App;
use app\common\repositories\activity\NewActivityRepository as repository;
use crmeb\basic\BaseController;
use think\db\BaseQuery;

class Activity extends BaseController
{
    /**
     * @var repository
     */
    protected $repository;

    /**
     * @param App $app
     * @param repository $repository
     */
    public function __construct(App $app, repository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }

    /**
     * @return mixed
     * @author: fupeng
     * @day: 2024/2/19
     */
    public function detail()
    {
        $couponList =[];
        $res =  $this->repository->getNewActivity(['is_del'=>0,'type'=>1]);
        $is_show = 0;
        if($res){
            $new_activity_id = $res->new_activity_id ;
            $uid = $this->request->userInfo()->uid;
            $coupon= StoreCouponUser::where('uid',$uid)
                ->where('activity_id',$new_activity_id)
                ->where('coupon_id',$res->coupon_id)
                ->find();
            if($coupon){
                $is_show = 1;
            }
            $couponList =   NewActivityCouponRelevance::getDB()->alias('cr')
                ->field('c.coupon_id,title,coupon_price,num,use_min_price')
                ->join('storeCoupon c','cr.coupon_id = c.coupon_id')
                ->where('new_activity_id',$res->new_activity_id)
                ->with(['couponUser' => function (BaseQuery $query) use ($uid,$new_activity_id) {
                    $query->field('coupon_id,start_time,end_time,status,is_fail')->where('activity_id', $new_activity_id)
                        ->where('uid', $uid);
                }])
                ->select()
                ->toArray();
            if($is_show){
                $flg = true;
                foreach ($couponList as $v){
                    if(!$v['couponUser']){
                        $flg = false;
                    }
                }
                if($flg){
                    $is_show = 0;
                }
            }
        }
        return app('json')->success(['is_show'=>$is_show,'activity'=>$res,'couponList'=>$couponList]);
    }


    /**
     * @return void
     * @author: fupeng
     * @day: 2024/2/19
     *
     */
    public function productLst(){
        $res =  $this->repository->getNewActivity(['is_del'=>0,'type'=>1]);
        if($res){
            $list = app()->make(NewActivityProductRepository::class)
                ->searchAll(['new_activity_id'=>$res->new_activity_id,'status'=>1,'is_del'=> 0,'admin_status'=>1,'spu_status'=>1,'mer_status'=>1],'*','NewActivityProduct.create_time desc');
            return app('json')->success($list);
        }
        return app('json')->fail('暂无进行中的活动');
    }

}
